package com.closer.server.mapper.organization;

import com.closer.server.biz.organization.dto.SearchRequest;
import com.closer.server.biz.organization.dto.UpdateRequest;
import com.closer.server.biz.organization.dto.vo.OrganizationVO;
import com.closer.server.support.sql.QueryWrapperHelper;
import com.mybatisflex.core.BaseMapper;
import com.closer.server.biz.organization.entity.Organization;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;

/**
 * 组织表 映射层。
 *
 * @author closer
 */
public interface OrganizationMapper extends BaseMapper<Organization> {


    /**
     * 更新组织信息
     */
    default boolean updateInfo(UpdateRequest params) {
        return UpdateChain.of(Organization.class)
                .set(Organization::getName, params.getName())
                .set(Organization::getDescription, params.getDescription())
                .where(Organization::getId).eq(params.getId())
                .update();
    }

    /**
     * 查询组织是否存在
     */
    default Organization existsOrganization(Long id) {
        var queryWrapper = new QueryWrapper().eq("id", id);
        return selectOneByQuery(queryWrapper);
    }

    /**
     * 更新组织创建者ID
     */
    default boolean updateCreatorId(Long id, Long creatorId){
        return UpdateChain.of(Organization.class)
                .set(Organization::getCreatorId, creatorId)
                .where(Organization::getId).eq(id)
                .update();
    }

    default Page<OrganizationVO> getOrganizationVOList(SearchRequest params) {
        var queryWrapper = QueryWrapper.create()
                .select("id","name","description","creator_id","current_members","create_time","update_time")
                .from("organization")
                .orderBy("organization.create_time desc");
                QueryWrapperHelper.likeIfPresent(queryWrapper, params.getName(), "organization.name");
                QueryWrapperHelper.likeIfPresent(queryWrapper, params.getStatus(), "organization.status");
        return paginateAs(params.getPageNumber(), params.getPageSize(),queryWrapper, OrganizationVO.class);
    }

    default boolean updateAddMemberCounts(Long organizationId) {
        return UpdateChain.of(Organization.class)
                .setRaw(Organization::getCurrentMembers,"current_members + 1")
                .where(Organization::getId).eq(organizationId)
                .update();
    }

    default boolean updateRemoveMemberCounts(Long organizationId) {
        return UpdateChain.of(Organization.class)
                .setRaw(Organization::getCurrentMembers,"current_members - 1")
                .where(Organization::getId).eq(organizationId)
                .update();
    }
}
